package com.zmj.sy.mom.srv.aps.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonNode;
import com.zmj.sy.mom.srv.aps.bean.entity.base.BaseEntity;
import com.zmj.sy.mom.srv.aps.bean.entity.log.LogNestExce;
import com.zmj.sy.mom.srv.aps.bean.entity.mes.*;
import com.zmj.sy.mom.srv.aps.bean.entity.order.*;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.Factory;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.LogApi;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.PlateStandard;
import com.zmj.sy.mom.srv.aps.bean.entity.third.*;
import com.zmj.sy.mom.srv.aps.bean.vo.base.BaseIdReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.base.Result;
import com.zmj.sy.mom.srv.aps.bean.vo.nest.newNest.ReceiveNestExcessReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.nest.newNest.ReceiveNestMoveReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.nest.newNest.ReceiveNestPartReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.nest.newNest.ReceiveNestPlateReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.plate.PlateListReqVo;
import com.zmj.sy.mom.srv.aps.bean.vo.plate.PlateListResVo;
import com.zmj.sy.mom.srv.aps.feign.ApsWmsApiClient;
import com.zmj.sy.mom.srv.aps.mapper.*;
import com.zmj.sy.mom.srv.aps.service.MomAndonService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 海克斯康 套料
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class HexagonNestOldUtils {

    private final ApsOrderMapper apsOrderMapper;
    private final ApsWorkOrderMapper apsWorkOrderMapper;
    private final OrderBomMapper orderBomMapper;
    private final FactoryMapper factoryMapper;
    private final OrderMapper orderMapper;
    private final PlateMapper plateMapper;
    private final PlateStandardMapper plateStandardMapper;
    private final WmsPlatePickMapper wmsPlatePickMapper;
    private final ImportMbdDxfMapper importMbdDxfMapper;
    private final PlatePhaseMapper platePhaseMapper;
    private final SinoCamMapper sinoCamMapper;
    private final SinoCamPushDrawingMapper sinoCamPushDrawingMapper;
    private final SinoCamPushPlanMapper sinoCamPushPlanMapper;
    private final SinoCamReceiveNestMapper sinoCamReceiveNestMapper;
    private final SinoCamReceiveNestPartMapper sinoCamReceiveNestPartMapper;
    private final SinoCamReceiveNestExcessMapper sinoCamReceiveNestExcessMapper;
    private final SinoCamReceiveNestNestMapper sinoCamReceiveNestNestMapper;
    private final SinoCamReceiveNestPlateMapper sinoCamReceiveNestPlateMapper;
    private final SinoCamReceiveNestMoveMapper sinoCamReceiveNestMoveMapper;
    private final ApsWorkDetailMapper apsWorkDetailMapper;
    private final WorkDetailTaskMapper workDetailTaskMapper;
    private final PickMapper pickMapper;
    private final LogNestExceMapper logNestExceMapper;
    private final HexagonPackagePushMapper hexagonPackagePushMapper;
    private final MomAndonService momAndonService;
    private final ApsWmsApiClient apsWmsApiClient;

    @Value("${project.feign.dxf-download}")
    private String dxfDownload;

    @Value("${project.feign.mes-url-png}")
    private String mesPNG;

    @Value("${project.feign.mes-url-dxf}")
    private String mesDXF;

    private BiConsumer<LogApi, String> consumer = (LogApi logApi, String body) -> {
        JsonNode jsonNode = JsonUtils.readTree(body);
        if (jsonNode.get("success").asBoolean()) { // 判断 body 中的 Success，为 true 还是 false
            logApi.setSuccess(true);
        } else {
            logApi.setSuccess(false);
            logApi.setErrorMsg(jsonNode.get("message").asText());
        }
    };

    public void pushMesMK(BaseIdReqVo reqVo, List<ApsWorkDetail> apsWorkDetailList) {

        List<ApsOrder> apsOrders = apsOrderMapper.lambdaQuery().eq(ApsOrder::getOrderId, reqVo.getId()).list();
        Map<Integer, ApsOrder> apsOrderIdMap = apsOrders.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));

        // 取 ID
        List<ApsWorkOrder> apsWorkOrders = apsWorkOrderMapper.selectBatchIds(apsWorkDetailList.stream().map(ApsWorkDetail::getApsWorkOrderId).distinct().collect(Collectors.toList()));
        Map<Integer, ApsWorkOrder> apsWorkOrderIdMap = apsWorkOrders.stream().collect(Collectors.toMap(ApsWorkOrder::getId, Function.identity()));

        // 取 PID
        List<ApsWorkOrder> parentApsWorkOrders = apsWorkOrderMapper.selectBatchIds(apsWorkDetailList.stream().map(ApsWorkDetail::getApsWorkOrderPid).distinct().collect(Collectors.toList()));
        Map<Integer, ApsWorkOrder> apsWorkOrderPidMap = parentApsWorkOrders.stream().collect(Collectors.toMap(ApsWorkOrder::getId, Function.identity()));

        List<OrderBom> orderBomList = orderBomMapper.lambdaQuery().in(OrderBom::getId, apsWorkOrders.stream().map(ApsWorkOrder::getBomId).distinct().collect(Collectors.toList())).list();
        Map<Integer, OrderBom> orderBomMap = orderBomList.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));

        // 获取工厂信息
        List<Factory> factoryList = factoryMapper.selectList(null);
        Map<Integer, Factory> factoryMap = factoryList.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));

        Order order = orderMapper.selectById(reqVo.getId());

        List<HexagonPackagePush> hexagonPackagePushList = hexagonPackagePushMapper.lambdaQuery().eq(HexagonPackagePush::getOrderId, order.getId()).list();
        Map<Integer, HexagonPackagePush> hexagonPackagePushMap = hexagonPackagePushList.stream().collect(Collectors.toMap(HexagonPackagePush::getApsOrderId, Function.identity()));

        // sendAndSaveDrawLan 推送图纸
        pushMesDrawMK(reqVo, apsWorkDetailList, factoryMap, order, apsOrderIdMap, apsWorkOrderPidMap, apsWorkOrderIdMap, orderBomMap);

        // sendAndSavePlanLan 推送计划
        pushMesPlanMK(reqVo, apsWorkDetailList, factoryMap, order, apsOrderIdMap, apsWorkOrderPidMap, apsWorkOrderIdMap, orderBomMap, hexagonPackagePushMap);

    }

    public void pushMesDrawMK(BaseIdReqVo reqVo, List<ApsWorkDetail> apsWorkDetailList, Map<Integer, Factory> factoryMap, Order order, Map<Integer, ApsOrder> apsOrderIdMap, Map<Integer, ApsWorkOrder> apsWorkOrderPidMap, Map<Integer, ApsWorkOrder> apsWorkOrderIdMap, Map<Integer, OrderBom> orderBomMap) {

        List<ApsWorkOrder> apsWorkOrders = apsWorkOrderMapper.selectBatchIds(apsWorkDetailList.stream().map(ApsWorkDetail::getApsWorkOrderId).distinct().collect(Collectors.toList()));
        List<OrderBom> orderBomList = orderBomMapper.lambdaQuery().in(OrderBom::getId, apsWorkOrders.stream().map(ApsWorkOrder::getBomId).distinct().collect(Collectors.toList())).list();
        for (OrderBom orderBom : orderBomList) {
            if (orderBom.getPlmId().endsWith("_170")) {
                orderBom.setPlmId(orderBom.getPlmId().substring(0, orderBom.getPlmId().indexOf("_170")));
            }
        }

        List<ImportMbdDxf> importMbdDxfList = importMbdDxfMapper.lambdaQuery().in(ImportMbdDxf::getPlmid, orderBomList.stream().map(OrderBom::getPlmId).distinct().collect(Collectors.toList())).list();
        Map<String, ImportMbdDxf> mbdDxfMap = importMbdDxfList.stream().collect(Collectors.toMap(ImportMbdDxf::getPlmid, Function.identity(), (a, b) -> b));

        List<SinoCamPushDrawing> pushedDrawingList = sinoCamPushDrawingMapper.lambdaQuery().eq(SinoCamPushDrawing::getOrderId, reqVo.getId()).list();
        Map<String, SinoCamPushDrawing> pushedDrawingMap = pushedDrawingList.stream().collect(Collectors.toMap(SinoCamPushDrawing::getPartId, Function.identity()));

        // apsWorkDetailList根据materNo字段进行去重
        apsWorkDetailList = apsWorkDetailList.stream().collect(Collectors.groupingBy(ApsWorkDetail::getMaterNo)).values().stream().map(apsWorkDetails -> apsWorkDetails.get(0)).collect(Collectors.toList());

        List<SinoCamPushDrawing> pushDrawList = new ArrayList<>();
        // 构建推送参数和数据库记录信息
        for (ApsWorkDetail apsWorkDetail : apsWorkDetailList) {
            ApsWorkOrder apsWorkOrder = apsWorkOrderIdMap.get(apsWorkDetail.getApsWorkOrderId());

            SinoCamPushDrawing pushDraw = new SinoCamPushDrawing();
            pushDraw.setOrderId(reqVo.getId());
            pushDraw.setFactoryIdk(factoryMap.get(apsWorkDetail.getFactoryId()).getMyCode());
            pushDraw.setProjectId(order.getConstructNo());
            pushDraw.setPartId(apsWorkOrder.getPlmId());
            pushDraw.setPartName(apsWorkOrder.getMaterName());
            pushDraw.setPartType(1);
            pushDraw.setDrawStatus(1);
            pushDraw.setPartStatus(1);
            pushDraw.setProductId(order.getMaterCode());
            pushDraw.setUniMaterCode(order.getId() + "#" + apsWorkOrder.getPlmId());
            pushDraw.setSuspensionStatus(0);
            pushDraw.setVersionNum(1L);
            pushDraw.setStatus(1);

            OrderBom bom = orderBomMap.get(apsWorkOrder.getBomId());
            pushDraw.setNorm(bom.getStandards());

            if (!StringUtils.hasText(bom.getTexture())) {
                String[] split = bom.getStandards().split("δ");
                pushDraw.setTexture(split[0].trim());
            } else {
                pushDraw.setTexture(bom.getTexture());
            }
            if (bom.getMaterHigh() == null) {
                String[] split = bom.getStandards().split("δ");
                if(split.length == 1){
                    throw SyExceptionUtils.e("{} 未查询到板厚", pushDraw.getPartId());
                }
                pushDraw.setThickNess(new BigDecimal(split[1].trim()));
            } else {
                pushDraw.setThickNess(new BigDecimal(bom.getMaterHigh()));
            }

            String code = bom.getPlmId();
            if (code.endsWith("_170")) {
                code = code.substring(0, code.indexOf("_170"));
            }
            ImportMbdDxf mbdDxf = mbdDxfMap.get(code);

            if (!ObjectUtils.isEmpty(mbdDxf)) {
                pushDraw.setFilePath(dxfDownload + mbdDxf.getPath());
                pushDraw.setChartId(mbdDxf.getDocNumber());
                pushDraw.setStatus(4);
                pushDrawList.add(pushDraw);
            } else {
                pushDraw.setStatus(4);
                pushDraw.setErrorMsg("未查询到下料图");
                pushDrawList.add(pushDraw);
            }

            if (pushedDrawingMap.get(pushDraw.getPartId()) != null) {
                pushDrawList.remove(pushDraw);
            }

        }

        if (!pushDrawList.isEmpty()) {
            sinoCamPushDrawingMapper.insertBatchSomeColumn(pushDrawList);
        }

    }

    public void pushMesPlanMK(BaseIdReqVo reqVo, List<ApsWorkDetail> apsWorkDetailList, Map<Integer, Factory> factoryMap, Order order, Map<Integer, ApsOrder> apsOrderIdMap, Map<Integer, ApsWorkOrder> apsWorkOrderPidMap, Map<Integer, ApsWorkOrder> apsWorkOrderIdMap, Map<Integer, OrderBom> orderBomMap, Map<Integer, HexagonPackagePush> hexagonPackagePushMap) {

        List<ApsWorkOrder> apsWorkOrders = apsWorkOrderMapper.selectBatchIds(apsWorkDetailList.stream().map(ApsWorkDetail::getApsWorkOrderId).distinct().collect(Collectors.toList()));
        List<OrderBom> orderBomList = orderBomMapper.lambdaQuery().in(OrderBom::getId, apsWorkOrders.stream().map(ApsWorkOrder::getBomId).distinct().collect(Collectors.toList())).list();
        for (OrderBom orderBom : orderBomList) {
            if (orderBom.getPlmId().endsWith("_170")) {
                orderBom.setPlmId(orderBom.getPlmId().substring(0, orderBom.getPlmId().indexOf("_170")));
            }
        }

        List<ImportMbdDxf> importMbdDxfList = importMbdDxfMapper.lambdaQuery().in(ImportMbdDxf::getPlmid, orderBomList.stream().map(OrderBom::getPlmId).distinct().collect(Collectors.toList())).list();
        Map<String, ImportMbdDxf> mbdDxfMap = importMbdDxfList.stream().collect(Collectors.toMap(ImportMbdDxf::getPlmid, Function.identity(), (a, b) -> b));

        List<PlateStandard> plateStandardList = plateStandardMapper.lambdaQuery().in(PlateStandard::getNorm, apsWorkOrders.stream().map(ApsWorkOrder::getStandards).distinct().collect(Collectors.toList())).list();
        Map<String, List<PlateStandard>> plateStandardMap = plateStandardList.stream().collect(Collectors.groupingBy(PlateStandard::getNorm));

        List<SinoCamPushDrawing> pushDrawList = sinoCamPushDrawingMapper.lambdaQuery().eq(SinoCamPushDrawing::getOrderId, reqVo.getId()).eq(SinoCamPushDrawing::getStatus, 4).list();
        Map<String, SinoCamPushDrawing> pushDrawingMap = pushDrawList.stream().collect(Collectors.toMap(SinoCamPushDrawing::getUniMaterCode, Function.identity()));

        List<SinoCamPushPlan> pushedPlanList = sinoCamPushPlanMapper.lambdaQuery().eq(SinoCamPushPlan::getOrderId, reqVo.getId()).list();
        Map<String, SinoCamPushPlan> pushedPlanMap = pushedPlanList.stream().collect(Collectors.toMap(SinoCamPushPlan::getNestPlanId, Function.identity()));

        List<HexagonPackagePush> hexPushList = hexagonPackagePushMapper.lambdaQuery().eq(HexagonPackagePush::getOrderId, reqVo.getId()).list();
        Map<Integer, HexagonPackagePush> hexPushMap = hexPushList.stream().collect(Collectors.toMap(HexagonPackagePush::getApsOrderId, Function.identity()));

        List<ApsWorkOrder> whileList = apsWorkOrderMapper.lambdaQuery().eq(ApsWorkOrder::getOrderId, reqVo.getId()).list();
        Map<Integer, ApsWorkOrder> whileMap = whileList.stream().collect(Collectors.toMap(ApsWorkOrder::getId, Function.identity()));

        List<SinoCamPushPlan> pushPlanList = new ArrayList<>();
        // 构建推送参数和数据库记录信息
        for (ApsWorkDetail apsWorkDetail : apsWorkDetailList) {
            ApsWorkOrder current = apsWorkOrderIdMap.get(apsWorkDetail.getApsWorkOrderId());
            ApsWorkOrder parent = apsWorkOrderPidMap.get(current.getPid());

            HexagonPackagePush hexPush = hexPushMap.get(apsWorkDetail.getApsOrderId());

            int id = current.getId();
            String path = "";
            while (true) {
                ApsWorkOrder pathCur = whileMap.get(id);
                if (pathCur.getPid() == null) {
                    break;
                }
                ApsWorkOrder pathPar = whileMap.get(pathCur.getPid());
                path = "→" + pathPar.getPlmId() + path;
                id = pathPar.getId();
            }

            SinoCamPushPlan pushPlan = new SinoCamPushPlan();
            pushPlan.setOrderId(reqVo.getId());
            pushPlan.setConsumeStatus(0);
            pushPlan.setNestPlanId(String.valueOf(apsWorkDetail.getId()));
            pushPlan.setProcessingNo(PkgUtils.gen(apsOrderIdMap.get(apsWorkDetail.getApsOrderId()).getSeq()));
            pushPlan.setProductId(order.getConstructNo());
            pushPlan.setComponentId(parent.getMaterCode());
            pushPlan.setComponentName(parent.getMaterName());
            pushPlan.setPartId(current.getPlmId());
            pushPlan.setPartName(current.getMaterName());
            pushPlan.setPartType(String.valueOf(1));
            pushPlan.setPlanAmount(apsWorkDetail.getTotalCount());
            pushPlan.setNeedDate(apsWorkDetail.getPlanStartDateTime());
            pushPlan.setFactoryIdk(factoryMap.get(apsWorkDetail.getFactoryId()).getMyCode());
            pushPlan.setPlanFinishAmount(new BigDecimal(0));
            pushPlan.setUniMaterCode(order.getId() + "#" + current.getPlmId());
            pushPlan.setVersionNum(1);
            pushPlan.setSuspensionStatus(0);
            pushPlan.setChartId(current.getPlmId());
            pushPlan.setApsOrderId(apsWorkDetail.getApsOrderId());
            HexagonPackagePush orDefault = hexagonPackagePushMap.getOrDefault(apsWorkDetail.getApsOrderId(), new HexagonPackagePush());
            pushPlan.setMesOrderCode(orDefault.getMesOrderCode());
            pushPlan.setMesPkgCode(orDefault.getPackageCode());
            pushPlan.setPath(hexPush.getPackageCode() + path);

            if (order.getOrderType() == 2) {
                pushPlan.setVersionBrief("V1");
                if (plateStandardMap.containsKey(current.getStandards())) {
                    pushPlan.setPlateLength(plateStandardMap.get(current.getStandards()).get(0).getLength());
                    pushPlan.setPlateWidth(plateStandardMap.get(current.getStandards()).get(0).getWidth());
                } else {
                    pushPlan.setPlateLength(10000);
                    pushPlan.setPlateWidth(2500);
                }
            } else {
                pushPlan.setVersionBrief("V2");
            }
            String code = current.getPlmId();
            if (code.endsWith("_170")) {
                code = code.substring(0, code.indexOf("_170"));
            }
            ImportMbdDxf mbdDxf = mbdDxfMap.get(code);
            pushPlan.setStatus(1);
            if (mbdDxf == null) {
                pushPlan.setStatus(4);
                pushPlan.setErrorMsg("未查询到套料图");
            } else if (!pushDrawingMap.containsKey(pushPlan.getUniMaterCode())) {
                pushPlan.setStatus(4);
                pushPlan.setErrorMsg("未推送套料图");
            } else {
                pushPlan.setStatus(4);
                pushPlan.setChartId(mbdDxf.getDocNumber());
            }
            pushPlanList.add(pushPlan);

            if (pushedPlanMap.get(pushPlan.getNestPlanId()) != null) {
                sinoCamPushPlanMapper.lambdaUpdate().eq(SinoCamPushPlan::getNestPlanId, pushPlan.getNestPlanId()).set(SinoCamPushPlan::getPath, pushPlan.getPath()).update();
                pushPlanList.remove(pushPlan);
            }

        }

        if (!pushPlanList.isEmpty()) {
            sinoCamPushPlanMapper.insertBatchSomeColumn(pushPlanList);
        }

    }

    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public void receiveMesNew(ReceiveNestPlateReqVo reqVo) {

        LogNestExce logNestExce = new LogNestExce();

        Pick pickOne = pickMapper.lambdaQuery().eq(Pick::getPickCode, reqVo.getPickListCode()).one();
        if (pickOne == null) {
            Pick newPick = new Pick();
            newPick.setPickCode(reqVo.getPickListCode());
            newPick.setSendDateTime(LocalDateTime.now());
            newPick.setSendStatus(2);
            newPick.setType(1);
            newPick.setUserCode("000000");
            newPick.setUsername("operator");
            pickMapper.insert(newPick);
        }

        // 查询钢板上零件的推送计划，先锁订单，再锁零件号
        List<ReceiveNestPartReqVo> partList = reqVo.getPart();

        List<SinoCamPushPlan> pushPlanList = sinoCamPushPlanMapper.lambdaQuery()
                .in(SinoCamPushPlan::getProductId, partList.stream().map(ReceiveNestPartReqVo::getConstructNo).collect(Collectors.toList()))
                .in(SinoCamPushPlan::getPartId, partList.stream().map(ReceiveNestPartReqVo::getPartId).collect(Collectors.toList()))
                .orderByAsc(SinoCamPushPlan::getProcessingNo)
                .list();
        if (CollUtil.isEmpty(pushPlanList)) {
            logNestExce.setAppId("MES套料");
            logNestExce.setPlateCode(reqVo.getPlateCode());
            logNestExce.setConstructNo(null);
            logNestExce.setNestId(reqVo.getNestId());
            logNestExce.setPartId("ALL");
            logNestExce.setQuantity(0);
            logNestExce.setNote("未查询到该板零件的推送计划：" + reqVo.getPlateCode());
            logNestExce.setInfoState(0);
            logNestExceMapper.insert(logNestExce);
            return;
        }

        Optional<SinoCamPushPlan> min = pushPlanList.stream().min(Comparator.comparing(SinoCamPushPlan::getNeedDate));
        LocalDateTime needDate = min.get().getNeedDate();
        String needDateTime = needDate.format(DatePattern.NORM_DATETIME_FORMATTER);

        SinoCam sc = new SinoCam();
        sc.setName("5-接收计划");
        sc.setType(5);
        sc.setStatus(1);
        sc.setResult(3);
        sc.setUniNum(sc.getOrderId() + "-" + sc.getType());

        sinoCamMapper.insert(sc);

        SinoCamReceiveNest scrn = new SinoCamReceiveNest();
        scrn.setSinoCamId(sc.getId());
        sinoCamReceiveNestMapper.insert(scrn);

        List<SinoCamReceiveNestPlate> plateAll = new ArrayList<>();
        List<SinoCamReceiveNestNest> nestAll = new ArrayList<>();

        int scId = sc.getId();
        int scrnId = scrn.getId();
        // 套料
        SinoCamReceiveNestNest nn = sinoCamReceiveNestNestMapper.lambdaQuery().eq(SinoCamReceiveNestNest::getNestId, reqVo.getNestId()).one();
        if (nn == null) {
            SinoCamReceiveNestNest nestEntity = MkBeanUtils.copyProperties(reqVo, SinoCamReceiveNestNest.class);
            nestEntity.setSinoCamId(sc.getId());
            nestEntity.setReceiveNestId(scrn.getId());
            nestEntity.setNestId(reqVo.getNestId());
            nestEntity.setFactoryIdk("170");
            nestEntity.setCutNozzleNorm(reqVo.getCutNozzleNorm());
            nestEntity.setCutNozzleNumber(reqVo.getCutNozzleNumber());
            nestEntity.setCutNozzleDistance(reqVo.getCutNozzleDistance());
            nestEntity.setWidth(reqVo.getWidth());
            nestEntity.setLength(reqVo.getLength());
            nestEntity.setNestDate(reqVo.getNestDateTime().replace(".0", ""));
            nestEntity.setChangeDate(reqVo.getChangeDateTime().replace(".0", ""));
            nestEntity.setNeedDate(needDateTime);
            nestEntity.setNester(reqVo.getNester());
            nestEntity.setChanger(reqVo.getChanger());
            nestEntity.setOptionId(reqVo.getGroupCode());
            nestEntity.setSplitGroupCode(reqVo.getGroupCode());
            nestEntity.setNestDxfUrl(mesDXF + reqVo.getDxfUrl());
            LocalDateTime nowDateTime = LocalDateTime.now();
            String nowTime = nowDateTime.format(DatePattern.PURE_DATE_FORMATTER);
            nestEntity.setBookSheet(nowTime);
            nestEntity.setReportPdfUrl(reqVo.getReportPdfUrl());
            nestEntity.setCuttingProgramUrl(reqVo.getCuttingProgramUrl());
            nestEntity.setRate(reqVo.getRate()); // 利用率，钢板减去余料，再与零件重量进行计算，得到利用率
            nestEntity.setVersionBrief("V2");
            sinoCamReceiveNestNestMapper.insert(nestEntity);
            nestAll.add(nestEntity);

            log.info("套料:{}", JsonUtils.toJsonString(nestEntity));
        } else {
            scId = nn.getSinoCamId();
            scrnId = nn.getReceiveNestId();
        }

        // 零件
        List<ReceiveNestPartReqVo> receiveNestParts = reqVo.getPart();
        List<SinoCamReceiveNestPart> receiveParts = new ArrayList<>();

        for (ReceiveNestPartReqVo e : receiveNestParts) {

            if (!StringUtils.hasText(e.getMesOrderCode())) {
                logNestExce.setAppId("MES套料");
                logNestExce.setPlateCode(reqVo.getPlateCode());
                logNestExce.setConstructNo(e.getConstructNo() != null ? e.getConstructNo() : null);
                logNestExce.setNestId(reqVo.getNestId());
                logNestExce.setPartId(e.getPartId());
                logNestExce.setQuantity(e.getQuantity());
                logNestExce.setNote("该零件没有MES施工号：" + e.getPartId());
                logNestExce.setInfoState(0);
                logNestExceMapper.insert(logNestExce);

                try {
                    String msg = e.getPartId() + "没有MES施工号。";
                    momAndonService.sendMsgFlyBook(msg);
                } catch (Exception exception) {
                }

                continue;
            }

            if (!StringUtils.hasText(e.getMesPkgCode())) {
                logNestExce.setAppId("MES套料");
                logNestExce.setPlateCode(reqVo.getPlateCode());
                logNestExce.setConstructNo(e.getConstructNo() != null ? e.getConstructNo() : null);
                logNestExce.setNestId(reqVo.getNestId());
                logNestExce.setPartId(e.getPartId());
                logNestExce.setQuantity(e.getQuantity());
                logNestExce.setNote("该零件没有MES包号：" + e.getPartId());
                logNestExce.setInfoState(0);
                logNestExceMapper.insert(logNestExce);

                try {
                    String msg = e.getPartId() + "没有MES包号。";
                    momAndonService.sendMsgFlyBook(msg);
                } catch (Exception exception) {
                }

                continue;
            }

            HexagonPackagePush hexagonPush = null;
            List<HexagonPackagePush> hexagonPackagePushList = hexagonPackagePushMapper.lambdaQuery()
                    .eq(HexagonPackagePush::getMesOrderCode, e.getMesOrderCode())
                    .eq(HexagonPackagePush::getPackageCode, e.getMesPkgCode())
                    .list();
            if (CollUtil.isNotEmpty(hexagonPackagePushList)) {
                if (hexagonPackagePushList.size() > 1) {
                    throw SyExceptionUtils.e("MES工单号和包号有重复：" + e.getMesOrderCode() + "_" + e.getPackageCode());
                }
                hexagonPush = hexagonPackagePushList.get(0);
            }

            if (hexagonPush == null) {
                logNestExce.setAppId("MES套料");
                logNestExce.setPlateCode(reqVo.getPlateCode());
                logNestExce.setConstructNo(e.getConstructNo() != null ? e.getConstructNo() : null);
                logNestExce.setNestId(reqVo.getNestId());
                logNestExce.setPartId(e.getPartId());
                logNestExce.setQuantity(e.getQuantity());
                logNestExce.setNote("该零件没有推送映射关系：" + e.getPartId());
                logNestExce.setInfoState(0);
                logNestExceMapper.insert(logNestExce);

                try {
                    String msg = e.getPartId() + "没有MES推送映射关系。";
                    momAndonService.sendMsgFlyBook(msg);
                } catch (Exception exception) {
                }

                continue;
            }

            List<SinoCamPushPlan> pushOneList = sinoCamPushPlanMapper.lambdaQuery()
                    .eq(SinoCamPushPlan::getApsOrderId, hexagonPush.getApsOrderId())
                    .eq(SinoCamPushPlan::getPath, e.getPath())
                    .eq(SinoCamPushPlan::getPartId, e.getPartId())
                    .list();
            if (CollUtil.isEmpty(pushOneList)) {
                logNestExce.setAppId("MES套料");
                logNestExce.setPlateCode(reqVo.getPlateCode());
                logNestExce.setConstructNo(e.getConstructNo() != null ? e.getConstructNo() : null);
                logNestExce.setNestId(reqVo.getNestId());
                logNestExce.setPartId(e.getPartId());
                logNestExce.setQuantity(1);
                logNestExce.setNote("零件计划为空：" + hexagonPush.getApsOrderId() + "#" + e.getPartId());
                logNestExce.setInfoState(0);
                logNestExceMapper.insert(logNestExce);

                try {
                    String msg = e.getPartId() + "未找到零件计划。";
                    momAndonService.sendMsgFlyBook(msg);
                } catch (Exception exception) {
                }

            } else {
                if (pushOneList.size() > 1) {
                    logNestExce.setAppId("MES套料");
                    logNestExce.setPlateCode(reqVo.getPlateCode());
                    logNestExce.setConstructNo(e.getConstructNo() != null ? e.getConstructNo() : null);
                    logNestExce.setNestId(reqVo.getNestId());
                    logNestExce.setPartId(e.getPartId());
                    logNestExce.setQuantity(1);
                    logNestExce.setNote("单包下零件计划不唯一：" + hexagonPush.getApsOrderId() + "#" + e.getPartId());
                    logNestExce.setInfoState(0);
                    logNestExceMapper.insert(logNestExce);
                } else {
                    SinoCamPushPlan pushOne = pushOneList.get(0);

                    SinoCamReceiveNestPart part = MkBeanUtils.copyProperties(e, SinoCamReceiveNestPart.class);
                    part.setSinoCamId(scId);
                    part.setReceiveNestId(scrnId);
                    part.setNestId(reqVo.getNestId());
                    part.setNestPlanId(pushOne.getNestPlanId());
                    part.setPartId(pushOne.getPartId());
                    part.setPartName(e.getPartName());
                    part.setQuantity(e.getQuantity());
                    part.setNetWeight(e.getNetWeight());
                    part.setArea(e.getArea() != null ? e.getArea() : BigDecimal.ZERO);
                    part.setRectangleArea(e.getRectangleArea() != null ? e.getRectangleArea() : BigDecimal.ZERO);
                    part.setRequireFactoryId(e.getFactoryCode());
                    part.setWidth(e.getWidth());
                    part.setLength(e.getLength());
                    if (e.getThickness() == null) {
                        part.setThickness(reqVo.getThickness());
                    } else {
                        part.setThickness(e.getThickness());
                    }
                    part.setPartMapUrl(mesPNG + e.getPngUrl());
                    part.setPlateCode(e.getPlateCode());
                    part.setSortingCount(0);// 分拣数量
                    part.setUniCode(pushOne.getUniMaterCode());
                    part.setSortState(0);

                    part.setOrderId(pushOne.getOrderId());
                    part.setWorkOrderCode(e.getWorkOrderCode());
                    part.setMesOrderCode(e.getMesOrderCode());
                    part.setMesPkgCode(e.getMesPkgCode());
                    part.setMesLineId(e.getLineId());

                    pushOne.setPlanFinishAmount(pushOne.getPlanFinishAmount().add(BigDecimal.valueOf(e.getQuantity())));
                    receiveParts.add(part);
                    pushOne.setStatus(4);
                    pushOne.setErrorMsg("已回填数据。");
                    sinoCamPushPlanMapper.updateById(pushOne);

                    if (pushOne.getPlanFinishAmount().compareTo(pushOne.getPlanAmount()) > 0) {
                        Order order = orderMapper.selectById(pushOne.getOrderId());
                        if (order.getOrderType() == 1) {
                            logNestExce.setAppId("MES套料");
                            logNestExce.setPlateCode(reqVo.getPlateCode());
                            logNestExce.setConstructNo(e.getConstructNo() != null ? e.getConstructNo() : null);
                            logNestExce.setNestId(reqVo.getNestId());
                            logNestExce.setPartId(e.getPartId());
                            logNestExce.setQuantity(pushOne.getPlanFinishAmount().subtract(pushOne.getPlanAmount()).intValue());
                            logNestExce.setNote("该零件套料数量超计划，超了：" + pushOne.getPlanFinishAmount().subtract(pushOne.getPlanAmount()).intValue() + "个。");
                            logNestExce.setInfoState(0);
                            logNestExceMapper.insert(logNestExce);
                        }
                    }
                }
            }
            /*if (CollUtil.isNotEmpty(pushOneList) && pushOneList.size() == 1) {

                SinoCamPushPlan pushOne = pushOneList.get(0);

                SinoCamReceiveNestPart part = MkBeanUtils.copyProperties(e, SinoCamReceiveNestPart.class);
                part.setSinoCamId(scId);
                part.setReceiveNestId(scrnId);
                part.setNestId(reqVo.getNestId());
                part.setNestPlanId(pushOne.getNestPlanId());
                part.setPartId(pushOne.getPartId());
                part.setPartName(e.getPartName());
                part.setQuantity(e.getQuantity());
                part.setNetWeight(e.getNetWeight());
                part.setArea(e.getArea() != null ? e.getArea() : BigDecimal.ZERO);
                part.setRectangleArea(e.getRectangleArea() != null ? e.getRectangleArea() : BigDecimal.ZERO);
                part.setRequireFactoryId(e.getFactoryCode());
                part.setWidth(e.getWidth());
                part.setLength(e.getLength());
                if (e.getThickness() == null) {
                    part.setThickness(reqVo.getThickness());
                } else {
                    part.setThickness(e.getThickness());
                }
                part.setPartMapUrl(mesPNG + e.getPngUrl());
                part.setPlateCode(e.getPlateCode());
                part.setSortingCount(0);// 分拣数量
                part.setUniCode(pushOne.getUniMaterCode());
                part.setSortState(0);

                part.setOrderId(pushOne.getOrderId());
                part.setWorkOrderCode(e.getWorkOrderCode());
                part.setMesOrderCode(e.getMesOrderCode());
                part.setMesPkgCode(e.getMesPkgCode());
                part.setMesLineId(e.getLineId());

                pushOne.setPlanFinishAmount(pushOne.getPlanFinishAmount().add(BigDecimal.valueOf(e.getQuantity())));
                receiveParts.add(part);
                pushOne.setStatus(4);
                pushOne.setErrorMsg("已回填数据。");
                sinoCamPushPlanMapper.updateById(pushOne);

                if (pushOne.getPlanFinishAmount().compareTo(pushOne.getPlanAmount()) > 0) {
                    logNestExce.setAppId("MES套料");
                    logNestExce.setPlateCode(reqVo.getPlateCode());
                    logNestExce.setConstructNo(e.getConstructNo() != null ? e.getConstructNo() : null);
                    logNestExce.setNestId(reqVo.getNestId());
                    logNestExce.setPartId(e.getPartId());
                    logNestExce.setQuantity(pushOne.getPlanFinishAmount().subtract(pushOne.getPlanAmount()).intValue());
                    logNestExce.setNote("该零件套料数量超计划，超了：" + pushOne.getPlanFinishAmount().subtract(pushOne.getPlanAmount()).intValue() + "个。");
                    logNestExce.setInfoState(0);
                    logNestExceMapper.insert(logNestExce);
                }

            } else {

                BigDecimal quantity = BigDecimal.valueOf(e.getQuantity()); // 当前钢板上套的数量

                List<SinoCamPushPlan> plans = sinoCamPushPlanMapper.lambdaQuery()
                        .eq(SinoCamPushPlan::getApsOrderId, hexagonPush.getApsOrderId())
                        .eq(SinoCamPushPlan::getPartId, e.getPartId())
                        .list();

                if (CollUtil.isEmpty(plans)) {
                    logNestExce.setAppId("MES套料");
                    logNestExce.setPlateCode(reqVo.getPlateCode());
                    logNestExce.setConstructNo(e.getConstructNo() != null ? e.getConstructNo() : null);
                    logNestExce.setNestId(reqVo.getNestId());
                    logNestExce.setPartId(e.getPartId());
                    logNestExce.setQuantity(e.getQuantity());
                    logNestExce.setNote("该零件未查询到包次推送计划：" + e.getPartId());
                    logNestExce.setInfoState(0);
                    logNestExceMapper.insert(logNestExce);
                    continue;
                }

                for (int index = 0; index < plans.size(); index++) {
                    SinoCamPushPlan plan = plans.get(index);
                    if (quantity.compareTo(BigDecimal.ZERO) < 1) {
                        continue;
                    }
                    if (index != plans.size() - 1 && plan.getPlanFinishAmount().compareTo(plan.getPlanAmount()) >= 0) {
                        continue;
                    }

                    BigDecimal planAmount = plan.getPlanAmount(); // 该计划的需要数量
                    BigDecimal planFinishAmount = plan.getPlanFinishAmount(); // 该计划已经套的数量
                    BigDecimal amount = planAmount.subtract(planFinishAmount); // 该计划当前所需差值
                    if (quantity.compareTo(amount) < 0) {
                        // 该钢板所套数量小于该计划当前的差值，所有数量全部归到该条数据
                        SinoCamReceiveNestPart part = MkBeanUtils.copyProperties(e, SinoCamReceiveNestPart.class);
                        part.setSinoCamId(scId);
                        part.setReceiveNestId(scrnId);
                        part.setNestId(reqVo.getNestId());
                        part.setNestPlanId(plan.getNestPlanId());
                        part.setPartId(plan.getPartId());
                        part.setPartName(e.getPartName());
                        part.setQuantity(quantity.intValue());
                        part.setNetWeight(e.getNetWeight());
                        part.setArea(e.getArea() != null ? e.getArea() : BigDecimal.ZERO);
                        part.setRectangleArea(e.getRectangleArea() != null ? e.getRectangleArea() : BigDecimal.ZERO);
                        part.setRequireFactoryId(e.getFactoryCode());
                        part.setWidth(e.getWidth());
                        part.setLength(e.getLength());
                        if (e.getThickness() == null) {
                            part.setThickness(reqVo.getThickness());
                        } else {
                            part.setThickness(e.getThickness());
                        }
                        part.setPartMapUrl(mesPNG + e.getPngUrl());
                        part.setPlateCode(e.getPlateCode());
                        part.setSortingCount(0);// 分拣数量
                        part.setUniCode(plan.getUniMaterCode());
                        part.setSortState(0);

                        part.setOrderId(plan.getOrderId());
                        part.setWorkOrderCode(e.getWorkOrderCode());
                        part.setMesOrderCode(e.getMesOrderCode());
                        part.setMesPkgCode(e.getMesPkgCode());
                        part.setMesLineId(e.getLineId());

                        plan.setPlanFinishAmount(planFinishAmount.add(quantity));
                        quantity = BigDecimal.ZERO;
                        receiveParts.add(part);
                        plan.setStatus(4);
                        plan.setErrorMsg("已回填数据。");
                        sinoCamPushPlanMapper.updateById(plan);
                    } else if (quantity.compareTo(amount) == 0) {
                        // 该钢板所套数量等于该计划当前的差值，所有数量全部归到该条数据，并且修改状态为填充完成
                        SinoCamReceiveNestPart part = MkBeanUtils.copyProperties(e, SinoCamReceiveNestPart.class);
                        part.setSinoCamId(scId);
                        part.setReceiveNestId(scrnId);
                        part.setNestId(reqVo.getNestId());
                        part.setNestPlanId(plan.getNestPlanId());
                        part.setPartId(plan.getPartId());
                        part.setPartName(e.getPartName());
                        part.setQuantity(quantity.intValue());
                        part.setNetWeight(e.getNetWeight());
                        part.setArea(e.getArea() != null ? e.getArea() : BigDecimal.ZERO);
                        part.setRectangleArea(e.getRectangleArea() != null ? e.getRectangleArea() : BigDecimal.ZERO);
                        part.setRequireFactoryId(e.getFactoryCode());
                        part.setWidth(e.getWidth());
                        part.setLength(e.getLength());
                        if (e.getThickness() == null) {
                            part.setThickness(reqVo.getThickness());
                        } else {
                            part.setThickness(e.getThickness());
                        }
                        part.setPartMapUrl(mesPNG + e.getPngUrl());
                        part.setPlateCode(e.getPlateCode());
                        part.setSortingCount(0);// 分拣数量
                        part.setUniCode(plan.getUniMaterCode());
                        part.setSortState(0);

                        part.setOrderId(plan.getOrderId());
                        part.setWorkOrderCode(e.getWorkOrderCode());
                        part.setMesOrderCode(e.getMesOrderCode());
                        part.setMesPkgCode(e.getMesPkgCode());
                        part.setMesLineId(e.getLineId());

                        plan.setPlanFinishAmount(planFinishAmount.add(quantity));
                        quantity = BigDecimal.ZERO;
                        receiveParts.add(part);
                        plan.setConsumeStatus(1);
                        plan.setStatus(4);
                        plan.setErrorMsg("已回填数据。");
                        sinoCamPushPlanMapper.updateById(plan);
                    } else if (quantity.compareTo(amount) > 0) {
                        // 该钢板所套数量大于该计划当前的差值，填充该数据所有差值，并且修改状态为填充完成，将该板剩余数量填充下一条数据
                        SinoCamReceiveNestPart part = MkBeanUtils.copyProperties(e, SinoCamReceiveNestPart.class);
                        part.setSinoCamId(scId);
                        part.setReceiveNestId(scrnId);
                        part.setNestId(reqVo.getNestId());
                        part.setNestPlanId(plan.getNestPlanId());
                        part.setPartId(e.getPartId());
                        part.setPartName(e.getPartName());
                        BigDecimal partQuantity = amount;
                        if (index == plans.size() - 1) {
                            partQuantity = quantity;
                            quantity = BigDecimal.ZERO;
                        } else {
                            quantity = quantity.subtract(amount);
                        }
                        part.setQuantity(partQuantity.intValue());
                        part.setNetWeight(e.getNetWeight());
                        part.setArea(e.getArea() != null ? e.getArea() : BigDecimal.ZERO);
                        part.setRectangleArea(e.getRectangleArea() != null ? e.getRectangleArea() : BigDecimal.ZERO);
                        part.setRequireFactoryId(e.getFactoryCode());
                        part.setWidth(e.getWidth());
                        part.setLength(e.getLength());
                        if (e.getThickness() == null) {
                            part.setThickness(reqVo.getThickness());
                        } else {
                            part.setThickness(e.getThickness());
                        }
                        part.setPartMapUrl(mesPNG + e.getPngUrl());
                        part.setPlateCode(e.getPlateCode());
                        part.setSortingCount(0);// 分拣数量
                        part.setUniCode(plan.getUniMaterCode());
                        part.setSortState(0);
                        // part.setQuantity(planAmount.intValue());
                        // quantity = quantity.subtract(amount);
                        receiveParts.add(part);
                        if (index == plans.size() - 1) {
                            plan.setPlanFinishAmount(planFinishAmount.add(partQuantity));
                        } else {
                            plan.setPlanFinishAmount(planAmount);
                        }

                        part.setOrderId(plan.getOrderId());
                        part.setWorkOrderCode(e.getWorkOrderCode());
                        part.setMesOrderCode(e.getMesOrderCode());
                        part.setMesPkgCode(e.getMesPkgCode());
                        part.setMesLineId(e.getLineId());

                        plan.setConsumeStatus(1);
                        plan.setStatus(4);
                        plan.setErrorMsg("已回填数据。");
                        sinoCamPushPlanMapper.updateById(plan);
                    }
                }

            }*/

        }

        if(CollUtil.isNotEmpty(receiveParts)){
            sinoCamReceiveNestPartMapper.insertBatchSomeColumn(receiveParts);
        }

        log.info("零件:{}", JsonUtils.toJsonString(receiveParts));

        String batchNo = "";
        try {
            PlateListReqVo plateDto = new PlateListReqVo();
            plateDto.setPlateId(reqVo.getPlateCode());
            plateDto.setPlateStock(1);
            Result<Page<PlateListResVo>> pageResult = apsWmsApiClient.plateList(plateDto);
            Page<PlateListResVo> dataPage = pageResult.getData();
            if (CollUtil.isNotEmpty(dataPage.getRecords())) {
                PlateListResVo plateListResVo = dataPage.getRecords().get(0);
                batchNo = plateListResVo.getBatchNo();
            }
        } catch (Exception e) {
        }

        // 钢板
        SinoCamReceiveNestPlate plate = MkBeanUtils.copyProperties(reqVo, SinoCamReceiveNestPlate.class);
        BigDecimal bigDecimal = new BigDecimal(1);
        BigDecimal amount = bigDecimal.setScale(0, RoundingMode.HALF_UP);
        plate.setAmount(amount);
        plate.setHeatNumber(reqVo.getHeatId());
        plate.setBatchNo(batchNo);
        plate.setSinoCamId(scId);
        plate.setReceiveNestId(scrnId);
        plate.setNestId(reqVo.getNestId());
        plate.setStockListNo(reqVo.getPlateCode());
        plate.setMaterielName(reqVo.getPlateCode());
        plate.setFactoryIdk("170");
        plate.setTexture(reqVo.getTexture());
        plate.setNorm(reqVo.getThickness().setScale(0, RoundingMode.HALF_UP).toString());
        plate.setWidth(reqVo.getWidth());
        plate.setLength(reqVo.getLength());
        plate.setStorehouseId(reqVo.getStoreCode());
        plate.setSequence(reqVo.getSequence());
        plate.setLayer(reqVo.getSequence());
        plate.setIsVirtual(false);
        plate.setRate(reqVo.getRate());
        plate.setSideLength(reqVo.getSideLength());
        plate.setStatus(1);// 领料状态
        plate.setPngUrl(mesPNG + reqVo.getPngUrl());
        plate.setPositionCode(reqVo.getPositionCode());
        plate.setNestArea(reqVo.getNxusedarea());

        sinoCamReceiveNestPlateMapper.insert(plate);
        plateAll.add(plate);

        log.info("钢板:{}", JsonUtils.toJsonString(plate));

        // 余料
        List<ReceiveNestExcessReqVo> excessListVo = reqVo.getExcess();
        if (CollUtil.isNotEmpty(excessListVo)) {
            ReceiveNestExcessReqVo excessVo = excessListVo.get(0);
            List<SinoCamReceiveNestExcess> list = sinoCamReceiveNestExcessMapper.lambdaQuery()
                    .eq(SinoCamReceiveNestExcess::getNestId, reqVo.getNestId())
                    .eq(SinoCamReceiveNestExcess::getStockListNo, reqVo.getPlateCode())
                    .eq(SinoCamReceiveNestExcess::getExMaterielId, excessVo.getExcessCode())
                    .list();
            if (CollUtil.isEmpty(list)) {
                SinoCamReceiveNestExcess excess = MkBeanUtils.copyProperties(excessVo, SinoCamReceiveNestExcess.class);
                excess.setSinoCamId(scId);
                excess.setReceiveNestId(scrnId);
                excess.setNestId(reqVo.getNestId());
                excess.setFactoryIdk("170");
                excess.setStockListNo(excessVo.getPlateCode());
                excess.setExMaterielId(excessVo.getExcessCode());
                excess.setTexture(excessVo.getTexture());
                excess.setNorm(excessVo.getThickness().toString());
                excess.setWidth(excessVo.getWidth());
                excess.setLength(excessVo.getLength());
                excess.setWeight(excessVo.getWeight());
                excess.setOutStock(0);
                sinoCamReceiveNestExcessMapper.insert(excess);

                log.info("余料:{}", JsonUtils.toJsonString(excess));
            }
        }

        // 走刀
        List<ReceiveNestMoveReqVo> moveList = reqVo.getMove();
        List<SinoCamReceiveNestMove> moves = new ArrayList<>();
        List<SinoCamReceiveNestMove> nm = sinoCamReceiveNestMoveMapper.lambdaQuery().eq(SinoCamReceiveNestMove::getNestId, reqVo.getNestId()).list();
        if (CollUtil.isEmpty(nm)) {
            if (CollUtil.isNotEmpty(moveList)) {
                int totalTime = 0;
                for (ReceiveNestMoveReqVo vo : moveList) {
                    SinoCamReceiveNestMove move = MkBeanUtils.copyProperties(vo, SinoCamReceiveNestMove.class);
                    move.setSinoCamId(scId);
                    move.setReceiveNestId(scrnId);
                    move.setNestId(reqVo.getNestId());
                    move.setCutLength(vo.getCutLength());
                    move.setFactoryIdk(vo.getFactoryCode());
                    move.setMoveTime(vo.getMoveTime());
                    move.setMoveType(vo.getMoveType());
                    move.setHoleCount(vo.getHoleCount());
                    move.setHoleTime(vo.getHoleTime());
                    move.setTotalHoleTime(vo.getTotalHoleTime());
                    move.setCutRate(vo.getCutRate());
                    move.setTotalCutTime(vo.getTotalCutTime());
                    totalTime = totalTime + vo.getTotalCutTime();
                    moves.add(move);
                }
                for (SinoCamReceiveNestMove a : moves) {
                    a.setTotalCutTime(totalTime);
                }
                sinoCamReceiveNestMoveMapper.insertBatchSomeColumn(moves);
            } else {
                SinoCamReceiveNestMove move1 = new SinoCamReceiveNestMove();
                SinoCamReceiveNestMove move2 = new SinoCamReceiveNestMove();

                move1.setSinoCamId(scId);
                move1.setReceiveNestId(scrnId);
                move1.setNestId(reqVo.getNestId());
                move1.setCutLength(BigDecimal.valueOf(1));
                move1.setFactoryIdk("170");
                move1.setMoveTime(1);
                move1.setMoveType(1);
                move1.setHoleCount(1);
                move1.setHoleTime(1);
                move1.setTotalHoleTime(1);
                move1.setCutRate(BigDecimal.valueOf(1));
                move1.setTotalCutTime(1);
                sinoCamReceiveNestMoveMapper.insert(move1);

                move2.setSinoCamId(scId);
                move2.setReceiveNestId(scrnId);
                move2.setNestId(reqVo.getNestId());
                move2.setCutLength(BigDecimal.valueOf(1));
                move2.setFactoryIdk("170");
                move2.setMoveTime(1);
                move2.setMoveType(2);
                move2.setHoleCount(1);
                move2.setHoleTime(0);
                move2.setTotalHoleTime(0);
                move2.setCutRate(BigDecimal.valueOf(1));
                move2.setTotalCutTime(1);
                sinoCamReceiveNestMoveMapper.insert(move2);

                logNestExce.setAppId("MES套料");
                logNestExce.setPlateCode(reqVo.getPlateCode());
                logNestExce.setConstructNo(receiveNestParts.get(0).getConstructNo());
                logNestExce.setNestId(reqVo.getNestId());
                logNestExce.setPartId(null);
                logNestExce.setQuantity(null);
                logNestExce.setNote("该钢板没有走刀信息！：" + reqVo.getPlateCode());
                logNestExce.setInfoState(0);
                logNestExceMapper.insert(logNestExce);

                try {
                    String msg = reqVo.getNestId() + "没有切割信息。";
                    momAndonService.sendMsgFlyBook(msg);
                } catch (Exception e) {
                }

            }

        }

        List<Integer> planIdList = receiveParts.stream().map(e -> Integer.parseInt(e.getNestPlanId())).distinct().collect(Collectors.toList());
        List<ApsWorkDetail> apsWorkDetails = apsWorkDetailMapper.selectBatchIds(planIdList);

        // ---------- 推送到钢板信息表----
        List<PlatePhase> platePhaseList = new ArrayList<>();
        List<ApsWorkDetail> apsWorkDetailList = new ArrayList<>();
        Map<String, PlatePhase> plateLlPhaseMap = new HashMap<>();
        Plate mesPlate = new Plate();
        List<ReceiveNestPartReqVo> nestParts = reqVo.getPart();
        mesPlate.setMaterCode(reqVo.getPlateCode());// 钢板编号
        mesPlate.setMaterName("钢板");// 钢板物料名称
        mesPlate.setLength(reqVo.getLength());
        mesPlate.setWidth(reqVo.getWidth());
        mesPlate.setNorm(String.valueOf(reqVo.getThickness().setScale(0, RoundingMode.HALF_UP)));// 厚度
        mesPlate.setTexture(reqVo.getTexture());
        mesPlate.setStatus(2);
        mesPlate.setHeatNumber(reqVo.getHeatId());

        SinoCamReceiveNestExcess nestExcess = sinoCamReceiveNestExcessMapper.lambdaQuery().eq(SinoCamReceiveNestExcess::getStockListNo, reqVo.getPlateCode()).one();
        BigDecimal weight = reqVo.getWeight();
        if (nestExcess != null) {
            weight = weight.subtract(nestExcess.getWeight());
        }

        mesPlate.setNestId(reqVo.getNestId());
        mesPlate.setNestRate(reqVo.getRate());// 利用率
        mesPlate.setNestDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER));// 套料日期
        mesPlate.setNestingDrawing(mesPNG + reqVo.getPngUrl());// 套料图纸，PNG格式
        mesPlate.setCutProcess(reqVo.getCuttingProgramUrl());// 切割程序下载地址
        mesPlate.setWeight(reqVo.getWeight());
        mesPlate.setNestWeight(weight.multiply(reqVo.getRate().divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP)));
        mesPlate.setPickDateTime(plate.getPickDateTime());// 领料时间
        mesPlate.setNestPlateId(plate.getId());
        mesPlate.setNestLock(0);

        PlatePhase llPhase = new PlatePhase();
        llPhase.setPlateCode(plate.getStockListNo());
        llPhase.setPhaseCode(WorkshopProp.LL_PHASE_CODE);
        llPhase.setPhaseName(WorkshopProp.LL_PHASE_NAME);
        llPhase.setGroupCode(WorkshopProp.LL_GROUP);
        llPhase.setPhaseSeq(platePhaseList.size() + 1);
        platePhaseList.add(llPhase);

        ApsWorkDetail llApsWorkDetail = new ApsWorkDetail();
        llApsWorkDetail.setMaterNo(plate.getStockListNo());
        llApsWorkDetail.setMaterName("钢板");
        llApsWorkDetail.setPhaseId(llPhase.getPhaseSeq());
        llApsWorkDetail.setPhaseSeq(llPhase.getPhaseSeq());
        llApsWorkDetail.setPhaseCode(WorkshopProp.LL_PHASE_CODE);
        llApsWorkDetail.setPartCount(new BigDecimal(1));
        llApsWorkDetail.setFinishCount(new BigDecimal(0));
        llApsWorkDetail.setTotalCount(new BigDecimal(1));
        llApsWorkDetail.setUniqueCode(plate.getStockListNo());
        llApsWorkDetail.setStatus(3);
        llApsWorkDetail.setPhaseName(WorkshopProp.LL_PHASE_NAME);
        llApsWorkDetail.setPlanStartDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).minusHours(7));
        llApsWorkDetail.setActualStartDateTime(LocalDateTime.now());
        llApsWorkDetail.setPlanEndDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).minusHours(6));
        llApsWorkDetail.setGroupCode(WorkshopProp.LL_GROUP);
        llApsWorkDetail.setAppendFlag(2);
        llApsWorkDetail.setType(1);
        llApsWorkDetail.setTotalWorkTime(60 * 60);
        llApsWorkDetail.setWorkTime(60 * 60);
        if (CollUtil.isNotEmpty(apsWorkDetails)) {
            llApsWorkDetail.setOrderId(apsWorkDetails.get(0).getOrderId());
            llApsWorkDetail.setApsOrderId(apsWorkDetails.get(0).getApsOrderId());
        }
        apsWorkDetailList.add(llApsWorkDetail);

        plateLlPhaseMap.put(plate.getStockListNo(), llPhase);

        // 添加预处理工序
        BigDecimal thickness = new BigDecimal(plate.getNorm());
        if (thickness.compareTo(new BigDecimal(100)) < 0) { //钢板厚度小于100走预处理
            PlatePhase phase = new PlatePhase();
            phase.setPlateCode(plate.getStockListNo());
            phase.setPhaseCode(WorkshopProp.YC_PHASE_CODE);
            phase.setPhaseName("预处理");
            phase.setGroupCode(WorkshopProp.YC_GROUP);
            phase.setPhaseSeq(platePhaseList.size() + 1);
            phase.setWorkTime(540);
            platePhaseList.add(phase);

            ApsWorkDetail ycApsWorkDetail = new ApsWorkDetail();
            ycApsWorkDetail.setMaterNo(plate.getStockListNo());
            ycApsWorkDetail.setMaterName("钢板");
            ycApsWorkDetail.setPhaseId(phase.getPhaseSeq());
            ycApsWorkDetail.setPhaseSeq(phase.getPhaseSeq());
            ycApsWorkDetail.setPhaseCode(WorkshopProp.YC_PHASE_CODE);
            ycApsWorkDetail.setPartCount(new BigDecimal(1));
            ycApsWorkDetail.setFinishCount(new BigDecimal(0));
            ycApsWorkDetail.setTotalCount(new BigDecimal(1));
            ycApsWorkDetail.setUniqueCode(plate.getStockListNo());
            ycApsWorkDetail.setStatus(2);
            ycApsWorkDetail.setPhaseName("预处理");
            ycApsWorkDetail.setPlanStartDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).minusHours(7));
            ycApsWorkDetail.setPlanEndDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).minusHours(6));
            ycApsWorkDetail.setGroupCode(WorkshopProp.YC_GROUP);
            ycApsWorkDetail.setAppendFlag(2);
            ycApsWorkDetail.setType(1);
            ycApsWorkDetail.setTotalWorkTime(60 * 60);
            ycApsWorkDetail.setWorkTime(60 * 60);
            if (CollUtil.isNotEmpty(apsWorkDetails)) {
                ycApsWorkDetail.setOrderId(apsWorkDetails.get(0).getOrderId());
                ycApsWorkDetail.setApsOrderId(apsWorkDetails.get(0).getApsOrderId());
            }
            apsWorkDetailList.add(ycApsWorkDetail);
        }

        // 添加切割工序
        PlatePhase splitPhase = new PlatePhase();
        splitPhase.setPlateCode(plate.getStockListNo());
        String phaseCode = getSplitCode(reqVo.getGroupCode(), reqVo.getNestId());
        splitPhase.setPhaseCode(phaseCode);
        splitPhase.setPhaseName(phaseCode.equals("JG") ? "激光切割" : "火焰切割");
        splitPhase.setGroupCode(reqVo.getGroupCode());
        splitPhase.setPhaseSeq(platePhaseList.size() + 1);
        List<SinoCamReceiveNestMove> nestMoveList = sinoCamReceiveNestMoveMapper.lambdaQuery().eq(SinoCamReceiveNestMove::getNestId, reqVo.getNestId()).list();
        if (CollUtil.isNotEmpty(nestMoveList)) {
            splitPhase.setWorkTime(nestMoveList.get(0).getTotalCutTime());
        } else {
            splitPhase.setWorkTime(0);
        }
        platePhaseList.add(splitPhase);

        ApsWorkDetail qgApsWorkDetail = new ApsWorkDetail();
        qgApsWorkDetail.setMaterNo(plate.getStockListNo());
        qgApsWorkDetail.setMaterName("钢板");
        qgApsWorkDetail.setPhaseId(splitPhase.getPhaseSeq());
        qgApsWorkDetail.setPhaseSeq(splitPhase.getPhaseSeq());
        qgApsWorkDetail.setPhaseCode(phaseCode);
        qgApsWorkDetail.setPartCount(new BigDecimal(1));
        qgApsWorkDetail.setFinishCount(new BigDecimal(0));
        qgApsWorkDetail.setTotalCount(new BigDecimal(1));
        qgApsWorkDetail.setUniqueCode(plate.getStockListNo());
        qgApsWorkDetail.setStatus(2);
        qgApsWorkDetail.setPhaseName(phaseCode.equals("JG") ? "激光切割" : "火焰切割");
        qgApsWorkDetail.setPlanStartDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER));
        qgApsWorkDetail.setPlanEndDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).plusHours(2));
        qgApsWorkDetail.setGroupCode(reqVo.getGroupCode());
        qgApsWorkDetail.setAppendFlag(2);
        qgApsWorkDetail.setType(1);
        if (CollUtil.isNotEmpty(apsWorkDetails)) {
            qgApsWorkDetail.setOrderId(apsWorkDetails.get(0).getOrderId());
            qgApsWorkDetail.setApsOrderId(apsWorkDetails.get(0).getApsOrderId());
        }
        qgApsWorkDetail.setTotalWorkTime(2 * 60 * 60);
        qgApsWorkDetail.setWorkTime(2 * 60 * 60);
        apsWorkDetailList.add(qgApsWorkDetail);

        // 添加分捡工序
        Map<String, String> fjGroup = new HashMap<>();
        fjGroup.put("1-1_HYQG_00", "1-1_RGFJ_00");
        fjGroup.put("1-2_JGQG_00", "1-2_ZDFJ_00");
        fjGroup.put("1-3_JGQG_00", "1-3_ZDFJ_00");

        PlatePhase fjPhase = new PlatePhase();
        fjPhase.setPlateCode(plate.getStockListNo());
        fjPhase.setPhaseCode(WorkshopProp.FJ_PHASE_CODE);
        fjPhase.setPhaseName("分捡");
        fjPhase.setGroupCode(fjGroup.get(reqVo.getGroupCode()));
        fjPhase.setPhaseSeq(platePhaseList.size() + 1);
        platePhaseList.add(fjPhase);

        ApsWorkDetail fjApsWorkDetail = new ApsWorkDetail();
        fjApsWorkDetail.setMaterNo(plate.getStockListNo());
        fjApsWorkDetail.setMaterName("钢板");
        fjApsWorkDetail.setPhaseId(fjPhase.getPhaseSeq());
        fjApsWorkDetail.setPhaseSeq(fjPhase.getPhaseSeq());
        fjApsWorkDetail.setPhaseCode(WorkshopProp.FJ_PHASE_CODE);
        fjApsWorkDetail.setPartCount(new BigDecimal(1));
        fjApsWorkDetail.setFinishCount(new BigDecimal(0));
        fjApsWorkDetail.setTotalCount(new BigDecimal(1));
        fjApsWorkDetail.setUniqueCode(plate.getStockListNo());
        fjApsWorkDetail.setStatus(2);
        fjApsWorkDetail.setPhaseName("分捡");
        fjApsWorkDetail.setPlanStartDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).plusHours(2));
        fjApsWorkDetail.setPlanEndDateTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER).plusHours(5));
        fjApsWorkDetail.setGroupCode(fjGroup.get(reqVo.getGroupCode()));
        fjApsWorkDetail.setAppendFlag(2);
        fjApsWorkDetail.setType(1);

        fjApsWorkDetail.setTotalWorkTime(3 * 60 * 60);
        fjApsWorkDetail.setWorkTime(3 * 60 * 60);
        if (CollUtil.isNotEmpty(apsWorkDetails)) {
            fjApsWorkDetail.setOrderId(apsWorkDetails.get(0).getOrderId());
            fjApsWorkDetail.setApsOrderId(apsWorkDetails.get(0).getApsOrderId());
        }
        apsWorkDetailList.add(fjApsWorkDetail);

        mesPlate.setWorkChain(platePhaseList.stream().map(PlatePhase::getPhaseCode).collect(Collectors.joining("-")));

        plateMapper.insert(mesPlate);
        plateLlPhaseMap.forEach(this::makeLingliao);
        Plate plateId = plateMapper.lambdaQuery().eq(Plate::getMaterCode, mesPlate.getMaterCode()).one();
        for (PlatePhase platePhase : platePhaseList) {
            platePhase.setPlateId(plateId.getId());
        }
        platePhaseMapper.insertBatch(platePhaseList);

        apsWorkDetailMapper.insertBatchSomeColumn(apsWorkDetailList);

        WmsPlatePick pick = new WmsPlatePick();

        pick.setPlateState(2);
        pick.setNextWorkPlace(reqVo.getGroupCode());
        pick.setNestPlateId(plate.getId());
        pick.setAmount(1);// 数量
        pick.setLength(plate.getLength());
        pick.setWidth(plate.getWidth());
        pick.setFastFlag(0);
        pick.setReceiveDate(LocalDateTime.now());
        pick.setPlannedStartTime(plate.getPickDateTime());// 领料时间
        pick.setType(1);
        pick.setMaterialCode(plate.getStockListNo());// 厚度
        pick.setPlateMaterial(plate.getTexture());
        pick.setPlateThick(plate.getNorm());// 厚度
        pick.setMaterialId(plate.getStockListNo());// 钢板编号（钢板物料号/材料编号？）
        pick.setPlateUsage(plate.getRate());// 利用率
        pick.setNesting(mesPNG + reqVo.getPngUrl());// 套料图号
        pick.setMaterName(plate.getMaterielName());// 钢板物料名称

        pick.setPickingListNo(reqVo.getPickListCode());
        pick.setPlanDate(null);
        pick.setPackageSn(null);
        pick.setWantDeliverDate(null);
        pick.setStoragePlace(plate.getPositionCode());
        pick.setSeq(plate.getSequence());
        pick.setPickListItem(reqVo.getPickNo());
        pick.setPlateWeight(mesPlate.getWeight());// 钢板重量
        pick.setCloutWeight(null);
        pick.setOutTime(LocalDateTime.now());
        pick.setPlateNote(null);
        pick.setPlateId(mesPlate.getId());// 钢板ID
        pick.setPlannedStartTime(LocalDateTime.parse(needDateTime, DatePattern.NORM_DATETIME_FORMATTER));// 需求日期
        pick.setNestId(reqVo.getNestId());
        pick.setPickDateTime(LocalDateTime.now());

        Pick standarfPick = pickMapper.lambdaQuery().eq(Pick::getPickCode, reqVo.getPickListCode()).one();
        pick.setPickId(standarfPick.getId());

        wmsPlatePickMapper.insert(pick);

        List<SinoCamPushDrawing> pushDrawingList = sinoCamPushDrawingMapper.lambdaQuery()
                .in(SinoCamPushDrawing::getProjectId, receiveNestParts.stream().map(ReceiveNestPartReqVo::getConstructNo).collect(Collectors.toList()))
                .in(SinoCamPushDrawing::getPartId, receiveNestParts.stream().map(ReceiveNestPartReqVo::getPartId).collect(Collectors.toList()))
                .list();
        for (SinoCamPushDrawing e : pushDrawingList) {
            e.setStatus(4);
            e.setErrorMsg("已回填图纸数据。");
            sinoCamPushDrawingMapper.updateById(e);
        }

    }

    public void makeLingliao(String materCode, PlatePhase llPhase) {
        Plate plate = plateMapper.lambdaQuery().eq(Plate::getMaterCode, materCode).one();
        SinoCamReceiveNestPlate nestPlate = sinoCamReceiveNestPlateMapper.lambdaQuery().eq(SinoCamReceiveNestPlate::getStockListNo, materCode).one();
        List<SinoCamReceiveNestPart> nestParts = sinoCamReceiveNestPartMapper.lambdaQuery().eq(SinoCamReceiveNestPart::getPlateCode, materCode).list();
        List<ApsWorkDetail> apsWorkDetails = apsWorkDetailMapper.selectBatchIds(nestParts.stream().map(SinoCamReceiveNestPart::getNestPlanId).distinct().collect(Collectors.toList()));
        List<Integer> orderIds = apsWorkDetails.stream().map(ApsWorkDetail::getOrderId).distinct().collect(Collectors.toList());
        WorkDetailTask plateTask = new WorkDetailTask();
        plateTask.setMaterCode(plate.getMaterCode());
        plateTask.setMaterName(plate.getMaterName());
        plateTask.setPhaseCode(llPhase.getPhaseCode());
        plateTask.setPhaseName(llPhase.getPhaseName());
        plateTask.setGroupCode(llPhase.getGroupCode());
        plateTask.setStationCode(WorkshopProp.LL_STATION_FIRST);
        plateTask.setStatus(2);
        plateTask.setType(1);
        plateTask.setPlanStartDateTime(plate.getNestDateTime());
        plateTask.setPlanEndDateTime(plateTask.getPlanStartDateTime().plusHours(2));
        if (!CollectionUtils.isEmpty(orderIds)) {
            List<Order> orders = orderMapper.selectBatchIds(orderIds);
            plateTask.setOrderCode(orders.stream().map(Order::getConstructNo).distinct().collect(Collectors.joining(",")));
        }
        plateTask.setNorm(plate.getNorm());
        plateTask.setTexture(plate.getTexture());
        plateTask.setWeight(plate.getNestWeight());
        plateTask.setNestPlateId(nestPlate.getId());
        plateTask.setNestId(plate.getNestId());

        plateTask.setPlmid(plate.getMaterCode());
        plateTask.setTotalCount(1);
        plateTask.setNextGroupCode(WorkshopProp.YC_GROUP);
        plateTask.setNextPhaseCode(WorkshopProp.YC_PHASE_CODE);
        plateTask.setPlateCode(plate.getMaterCode());
        plateTask.setLength(plate.getLength());
        plateTask.setWidth(plate.getWidth());
        plateTask.setThickness(BigDecimal.valueOf(Integer.parseInt(plate.getNorm())));
        workDetailTaskMapper.insert(plateTask);
    }

    public String getSplitCode(String optionId, String nestId) {

        Map<String, String> params = new HashMap<>();
        params.put("1-1_HYQG_00", "HG");
        params.put("1-2_JGQG_00", "JG");
        params.put("1-3_JGQG_00", "JG");

        String groupCode = params.get(optionId);
        if (groupCode == null) {
            try {
                String msg = nestId + "切割工作组信息异常：" + optionId;
                momAndonService.sendMsgFlyBook(msg);
            } catch (Exception e) {
            }
            throw SyExceptionUtils.e("未知的切割工作组：{}", optionId);
        }

        return groupCode;
    }

    public SinoCamPushDrawing saveDraw(ApsWorkOrder apsWorkOrder, Order order, OrderBom bom, Map<String, ImportMbdDxf> mbdDxfMap) {

        SinoCamPushDrawing one = sinoCamPushDrawingMapper.lambdaQuery()
                .eq(SinoCamPushDrawing::getUniMaterCode, order.getId() + "#" + apsWorkOrder.getPlmId())
                .one();
        if (one != null) {
            return one;
        }

        SinoCamPushDrawing pushDraw = new SinoCamPushDrawing();

        pushDraw.setOrderId(order.getId());
        pushDraw.setFactoryIdk(order.getFactoryCode());
        pushDraw.setProjectId(order.getConstructNo());
        pushDraw.setPartId(apsWorkOrder.getPlmId());
        pushDraw.setPartName(apsWorkOrder.getMaterName());
        pushDraw.setPartType(1);
        pushDraw.setProductId(order.getPlmId());
        pushDraw.setUniMaterCode(order.getId() + "#" + apsWorkOrder.getPlmId());
        pushDraw.setSuspensionStatus(0);
        pushDraw.setVersionNum(1L);
//            pushDraw.setType(1);
        pushDraw.setStatus(1);

        String[] split = bom.getStandards().split("δ");

        pushDraw.setNorm(bom.getStandards());

        if (!StringUtils.hasText(bom.getTexture())) {
            pushDraw.setTexture(split[0].trim());
        } else {
            pushDraw.setTexture(bom.getTexture());
        }
        if (bom.getMaterHigh() == null) {
            pushDraw.setThickNess(new BigDecimal(split[1].trim()));
        } else {
            pushDraw.setThickNess(new BigDecimal(bom.getMaterHigh()));
        }

        String code = bom.getPlmId();
        if (code.endsWith("_170")) {
            code = code.substring(0, code.indexOf("_170"));
        }
        ImportMbdDxf mbdDxf = mbdDxfMap.get(code);

        if (!ObjectUtils.isEmpty(mbdDxf)) {
            pushDraw.setFilePath(dxfDownload + mbdDxf.getPath());
            pushDraw.setChartId(mbdDxf.getDocNumber());
            pushDraw.setDrawVersion(mbdDxf.getDocVersion());
        } else {
            pushDraw.setStatus(5);
            pushDraw.setErrorMsg("未查询到下料图");
        }

        sinoCamPushDrawingMapper.insert(pushDraw);
        return pushDraw;
    }

    public void savePlan(ApsWorkDetail apsWorkDetail, Order order, ApsOrder apsOrder, ApsWorkOrder current, ApsWorkOrder parent, Map<String, List<PlateStandard>> plateStandardMap, Map<String, ImportMbdDxf> mbdDxfMap) {
//        ApsWorkOrder current = apsWorkOrderIdMap.get(apsWorkDetail.getApsWorkOrderId());
//        ApsWorkOrder parent = apsWorkOrderPidMap.get(current.getPid());

        SinoCamPushPlan pushPlan = new SinoCamPushPlan();

        pushPlan.setOrderId(order.getId());
        pushPlan.setConsumeStatus(1);
        pushPlan.setNestPlanId(String.valueOf(apsWorkDetail.getId()));
        pushPlan.setProcessingNo(PkgUtils.gen(apsOrder.getSeq()));
        pushPlan.setProductId(order.getPlmId());
        pushPlan.setComponentId(parent.getPlmId());
        pushPlan.setComponentName(parent.getMaterName());
        pushPlan.setPartId(current.getPlmId());
        pushPlan.setPartName(current.getMaterName());
        pushPlan.setPartType(String.valueOf(1));
        pushPlan.setPlanAmount(apsWorkDetail.getTotalCount());
        pushPlan.setNeedDate(apsWorkDetail.getPlanStartDateTime());
        pushPlan.setFactoryIdk(order.getFactoryCode());
        pushPlan.setPlanFinishAmount(new BigDecimal(0));
        pushPlan.setUniMaterCode(order.getId() + "#" + current.getPlmId());
        pushPlan.setVersionNum(1);
        pushPlan.setSuspensionStatus(0);
        pushPlan.setChartId(current.getPlmId());
        pushPlan.setStatus(1);

        if (order.getOrderType() == 2) {
            pushPlan.setVersionBrief(String.valueOf(1));
            if (plateStandardMap.containsKey(current.getStandards())) {
                pushPlan.setPlateLength(plateStandardMap.get(current.getStandards()).get(0).getLength());
                pushPlan.setPlateWidth(plateStandardMap.get(current.getStandards()).get(0).getWidth());
            } else {
                pushPlan.setPlateLength(10000);
                pushPlan.setPlateWidth(2500);
            }
        } else {
            pushPlan.setVersionBrief(String.valueOf(2));
        }
        String code = current.getPlmId();
        if (code.endsWith("_170")) {
            code = code.substring(0, code.indexOf("_170"));
        }
        ImportMbdDxf mbdDxf = mbdDxfMap.get(code);
        if (mbdDxf == null) {
            pushPlan.setStatus(5);
            pushPlan.setErrorMsg("未查询到套料图");
        } else {
            pushPlan.setChartId(mbdDxf.getDocNumber());
        }
//        pushPlanList.add(pushPlan);
        sinoCamPushPlanMapper.insert(pushPlan);
    }

}
